package com.example.logindemo.controller;

import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.imageio.ImageIO;

@RestController
@RequestMapping({"/file", "/uploads"})
public class FileController {

    private final Path fileStorageLocation;
    private final Path avatarStorageLocation;

    public FileController() {
        // 初始化文件存储位置
        this.fileStorageLocation = Paths.get("uploads").toAbsolutePath().normalize();
        this.avatarStorageLocation = Paths.get("uploads/avatars").toAbsolutePath().normalize();
        
        // 创建必要的目录（如果不存在）
        try {
            if (!Files.exists(this.fileStorageLocation)) {
                Files.createDirectories(this.fileStorageLocation);
            }
            if (!Files.exists(this.avatarStorageLocation)) {
                Files.createDirectories(this.avatarStorageLocation);
            }
        } catch (IOException ex) {
            throw new RuntimeException("无法创建文件存储目录", ex);
        }
    }

    @GetMapping("/{fileName:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
        try {
            // 处理默认头像请求
            if (fileName.equals("default-avatar.png")) {
                // 返回一个简单的默认头像
                byte[] defaultAvatar = generateDefaultAvatar();
                HttpHeaders headers = new HttpHeaders();
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"default-avatar.png\"");
                return ResponseEntity.ok()
                        .headers(headers)
                        .contentType(MediaType.IMAGE_PNG)
                        .body(new org.springframework.core.io.ByteArrayResource(defaultAvatar));
            }
            
            // 确定文件路径
            Path filePath;
            boolean isAvatar = false;
            
            // 检查是否是头像路径 - 增强路径处理逻辑
            if (fileName.startsWith("avatars/")) {
                // 如果文件名已经包含avatars/前缀，直接获取文件名部分
                String avatarFileName = fileName.substring(8);
                filePath = this.avatarStorageLocation.resolve(avatarFileName).normalize();
                isAvatar = true;
                System.out.println("请求头像文件: " + fileName + "，解析到路径: " + filePath);
            } else {
                // 先尝试在avatar目录查找，再尝试在根目录查找
                filePath = this.avatarStorageLocation.resolve(fileName).normalize();
                if (Files.exists(filePath)) {
                    isAvatar = true;
                    System.out.println("在头像目录找到文件: " + fileName + "，路径: " + filePath);
                } else {
                    filePath = this.fileStorageLocation.resolve(fileName).normalize();
                    System.out.println("在文件存储目录查找文件: " + fileName + "，路径: " + filePath);
                }
            }
            
            Resource resource = new UrlResource(filePath.toUri());

            if (!resource.exists()) {
                return ResponseEntity.notFound().build();
            }

            HttpHeaders headers = new HttpHeaders();
            MediaType mediaType;
            
            // 确定文件MIME类型
            if (isAvatar || fileName.toLowerCase().matches(".*\\.(jpg|jpeg|png|gif|webp|bmp|svg)$")) {
                String extension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
                switch (extension) {
                    case "jpg":
                    case "jpeg":
                        mediaType = MediaType.IMAGE_JPEG;
                        break;
                    case "png":
                        mediaType = MediaType.IMAGE_PNG;
                        break;
                    case "gif":
                        mediaType = MediaType.IMAGE_GIF;
                        break;
                    case "svg":
                        mediaType = MediaType.parseMediaType("image/svg+xml");
                        break;
                    default:
                        mediaType = MediaType.IMAGE_JPEG;
                }
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + fileName + "\"");
            } else {
                mediaType = MediaType.APPLICATION_OCTET_STREAM;
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");
            }

            return ResponseEntity.ok()
                    .headers(headers)
                    .contentType(mediaType)
                    .body(resource);
        } catch (Exception ex) {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 生成一个简单的默认头像（灰色背景，白色字母）
     */
    private byte[] generateDefaultAvatar() {
        try {
            // 创建一个简单的128x128像素的灰色头像
            java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(128, 128, java.awt.image.BufferedImage.TYPE_INT_RGB);
            java.awt.Graphics2D g = image.createGraphics();
            
            // 填充灰色背景
            g.setColor(new java.awt.Color(200, 200, 200));
            g.fillRect(0, 0, 128, 128);
            
            // 绘制白色字母 'U'
            g.setColor(java.awt.Color.WHITE);
            g.setFont(new java.awt.Font("Arial", java.awt.Font.BOLD, 60));
            java.awt.FontMetrics metrics = g.getFontMetrics();
            int x = (128 - metrics.stringWidth("U")) / 2;
            int y = ((128 - metrics.getHeight()) / 2) + metrics.getAscent();
            g.drawString("U", x, y);
            g.dispose();
            
            // 转换为PNG字节数组
            java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
            javax.imageio.ImageIO.write(image, "png", baos);
            return baos.toByteArray();
        } catch (Exception e) {
            // 如果生成失败，返回一个空的字节数组
            return new byte[0];
        }
    }
    
    @GetMapping("/download/{fileName:.+}")
    public ResponseEntity<Resource> forceDownload(@PathVariable String fileName) {
        try {
            // 确定文件路径
            Path filePath;
            
            // 检查是否是头像路径
            if (fileName.startsWith("avatars/")) {
                filePath = this.avatarStorageLocation.resolve(fileName.substring(8)).normalize();
            } else {
                filePath = this.fileStorageLocation.resolve(fileName).normalize();
            }
            
            Resource resource = new UrlResource(filePath.toUri());

            if (!resource.exists()) {
                return ResponseEntity.notFound().build();
            }

            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");

            return ResponseEntity.ok()
                    .headers(headers)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } catch (Exception ex) {
            return ResponseEntity.notFound().build();
        }
    }
}